import React, { useEffect, useRef, useState } from 'react'
import { handleError } from '@zj/utils'
import { postChartData } from './service'

interface IntervalProps {
  noteCode: string
  pullInterval?: number
}

const useIntervalRequest = (props: IntervalProps) => {
  const { noteCode } = props
  const ref = useRef<any>(null)
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState([])

  useEffect(() => {
    if (props.pullInterval && props.pullInterval < 0) return

    if (props.pullInterval) {
      ref.current = window.setInterval(() => {
        handlePostChartData(noteCode)
      }, props.pullInterval)
    } else {
      handlePostChartData(noteCode)
    }

    return () => {
      if (props.pullInterval) {
        clearInterval(ref.current)
      }
    }
  }, [])

  const handlePostChartData = async (noteCode) => {
    try {
      const { result } = await postChartData(noteCode)
      setResult(result)
    } catch (err) {
      console.log(err)
    } finally {
      setLoading(false)
    }
  }
  return {
    result,
    loading,
  }
}

export default useIntervalRequest
